<template>
  <div class="app-container">
    <el-row :gutter="10" type="flex" style="height: 98%; width: 100%">
      <el-tree
        style="flex: 0 0 150px; height: 100%; overflow: auto"
        :height="tableH"
        :data="deptOptions"
        :props="defaultProps"
        ref="tree"
        default-expand-all
        @node-click="handleNodeClick"
      />
      <div style="width: calc(100% - 150px)">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-search"
              size="mini"
              @click="handleSearch"
              v-hasPermi="['produce:jtPlanMaintain:query']"
            >
              查询
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['produce:jtPlanMaintain:edit']"
            >
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['produce:jtPlanMaintain:delete']"
            >
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleStop"
              v-hasPermi="['produce:jtPlanMaintain:stop']"
            >
              暂停
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleMerge"
              :disabled="multiple"
              v-hasPermi="['produce:jtPlanMaintain:merge']"
            >
              合并工单
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              plain
              size="mini"
              @click="handleCMerge"
              :disabled="multiple"
              v-hasPermi="['produce:jtPlanMaintain:mergeCancel']"
            >
              取消合并
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleMobile"
              :disabled="multiple"
              v-hasPermi="['produce:jtPlanMaintain:mobile']"
            >
              移动
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleOrder"
              v-hasPermi="['produce:jtPlanMaintain:index']"
              >工单排序</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleOrderFinish"
              :disabled="orderArr.length == 0"
              v-hasPermi="['produce:jtPlanMaintain:index']"
            >
              排序完成
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['produce:jtPlanMaintain:excel']"
            >
              导出
            </el-button>
          </el-col>
          <Tag type="dot" size="default" color="#09aa46">启动</Tag>
          <Tag type="dot" size="default" color="#bb0331">等待</Tag>
          <Tag type="dot" size="default" color="#4169E1">暂停</Tag>
          <Tag type="dot" size="default" color="#FAFFF0">完成</Tag>

          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          @scrollBottom="load"
          highlight-current-row
          border
          stripe
          :cell-style="iCellStyle"
          v-loading="loading"
          @row-click="clickRow"
          :height="tableH"
          :data="moeDetList"
          @selection-change="handleSelectionChange"
          show-summary
          :summary-method="getSummaries"
          :header-cell-style="{ 'text-align': 'center' }"
        >
          <el-table-column
            label="#"
            width="40"
            align="center"
            type="index"
            fixed="left"
          />
          <el-table-column
            type="selection"
            width="55"
            align="center"
            fixed="left"
          />
          <el-table-column
            label="父项客户编码"
            :show-overflow-tooltip="true"
            width="100"
            align="center"
            prop="somCustwldm"
            fixed="left"
          />
          <el-table-column
            label="客户编码"
            :show-overflow-tooltip="true"
            width="110"
            align="center"
            prop="itmCustwldm"
          />
          <el-table-column
            label="物料代码"
            :show-overflow-tooltip="true"
            width="120"
            align="center"
            prop="moeWldm"
          />
          <el-table-column
            label="品名规格"
            :show-overflow-tooltip="true"
            min-width="220"
            align="center"
            prop="itmPmgg"
          />
          <el-table-column
            label="模具编号"
            :show-overflow-tooltip="true"
            width="150"
            align="center"
            prop="moeMjbh"
          />
          <el-table-column
            label="穴数"
            :show-overflow-tooltip="true"
            width="50"
            align="center"
            prop="moeXs"
          />
          <el-table-column
            label="标准穴数"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeBzxs"
          />
          <el-table-column
            label="机台"
            :show-overflow-tooltip="true"
            width="70"
            align="center"
            prop="moeJtbh"
          />
          <el-table-column
            label="组合ID"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeGlid"
          />
          <el-table-column
            label="制造单号"
            :show-overflow-tooltip="true"
            width="120"
            align="center"
            prop="moeZzdh"
          >
            <template #default="scope">
              <PopProductBom :cldZzdh="scope.row.moeZzdh" />
            </template>
          </el-table-column>
          <el-table-column
            label="销售单号"
            :show-overflow-tooltip="true"
            width="120"
            align="center"
            prop="moeSodh"
          />
          <el-table-column
            label="排程日期"
            :show-overflow-tooltip="true"
            align="center"
            prop="moeScrq"
            width="160"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.moeScrq, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="完工日期"
            :show-overflow-tooltip="true"
            align="center"
            prop="moeWgrq"
            width="160"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.moeWgrq, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="交货日期"
            :show-overflow-tooltip="true"
            align="center"
            prop="somJhrq"
            width="160"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.somJhrq, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="生管备注"
            :show-overflow-tooltip="true"
            width="100"
            align="center"
            prop="moeDesc"
          />
          <el-table-column
            label="用时"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeSqys"
          />
          <el-table-column
            label="成型时间"
            :show-overflow-tooltip="true"
            width="100"
            align="center"
            prop="moeCxsj"
          />
          <el-table-column
            label="存放位置"
            :show-overflow-tooltip="true"
            width="100"
            align="center"
            prop="moeJtbh"
          />
          <el-table-column
            label="预计开始时间"
            :show-overflow-tooltip="true"
            align="center"
            prop="moeKssj"
            width="160"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.moeKssj, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="预计结束时间"
            :show-overflow-tooltip="true"
            align="center"
            prop="moeJssj"
            width="160"
          >
            <template #default="scope">
              <span>{{
                parseTime(scope.row.moeJssj, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="序号"
            :show-overflow-tooltip="true"
            width="50"
            align="center"
            prop="moeScxh"
          />
          <el-table-column
            label="组别"
            :show-overflow-tooltip="true"
            width="60"
            align="center"
            prop="moeBbdm"
          />
          <el-table-column
            label="计划数量"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeScsl"
            fixed="right"
          />
          <el-table-column
            label="良品数量"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeLpsl"
            fixed="right"
          />
          <el-table-column
            label="未完成数"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeSysl"
            fixed="right"
          />
          <el-table-column
            label="入库数"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeRksl"
            fixed="right"
          />
          <el-table-column
            label="标准产能"
            :show-overflow-tooltip="true"
            width="80"
            align="center"
            prop="moeDaycn"
            fixed="right"
          />
        </el-table>
      </div>
    </el-row>
    <!-- 查询对话框   -->
    <el-dialog
      :title="title"
      v-model="openSearch"
      :close-on-click-modal="false"
      draggable
      width="650px"
      append-to-body
    >
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-col :span="24">
          <el-form-item label="排程日期" prop="dateRange">
            <el-date-picker
              clearable
              size="small"
              v-model="dateRange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="制造单号" prop="moeZzdh">
            <el-input
              v-model="queryParams.moeZzdh"
              placeholder="请输入制造单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售单号" prop="moeSodh">
            <el-input
              v-model="queryParams.moeSodh"
              placeholder="请输入销售单号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="机台编号" prop="moeJtbh">
            <el-input
              v-model="queryParams.moeJtbh"
              placeholder="机台编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模具编号" prop="moeMjbh">
            <el-input
              v-model="queryParams.moeMjbh"
              placeholder="请输入模具编号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="itmPmgg" label-width="95px">
            <span slot="label">
              <el-tooltip
                content="综合查询包含物料代码，品名规格，客户编码查询"
                placement="top"
              >
                <i class="el-icon-question"></i>
              </el-tooltip>
              综合查询
            </span>
            <el-input
              v-model="queryParams.itmPmgg"
              clearable
              size="small"
              type="textarea"
              style="width: 450px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-checkbox v-model="queryParams.flag">只显示未完成工单</el-checkbox>
        <el-checkbox v-model="queryParams.scflag">只显示生产中工单</el-checkbox>
        <el-col :span="24">
          <el-form-item
            style="margin-top: 25px; display: flex; justify-content: flex-end"
          >
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="handleQuery">确认</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-dialog>
    <!-- 修改工单对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      draggable
      width="680px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-col :span="12">
          <el-form-item label="机台编号" prop="moeJtbh">
            <el-input v-model="form.moeJtbh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属组别" prop="moeBbdm">
            <el-input v-model="form.moeBbdm" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="制造单号" prop="moeZzdh">
            <el-input v-model="form.moeZzdh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="销售单号" prop="moeSodh">
            <el-input v-model="form.moeSodh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料代码" prop="moeWldm">
            <el-input v-model="form.moeWldm" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="完工日期" prop="moeWgrq">
            <el-date-picker
              clearable
              size="small"
              v-model="form.moeWgrq"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择完工日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="品名规格" prop="itmPmgg">
            <el-input v-model="form.itmPmgg" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计划数量" prop="moeScsl">
            <el-input v-model="form.moeScsl" placeholder="请输入计划数量" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="模具编号" prop="moeMjbh">
            <el-select
              v-model="form.moeMjbh"
              placeholder="请选择模具"
              @change="changeSelect"
            >
              <el-option
                v-for="dict in mjmList"
                :key="dict.mjm_mjbh"
                :label="dict.mjm_mjbh"
                :value="dict.mjm_mjbh"
              />
            </el-select>
          </el-form-item>
          <!--              <el-form-item label="模具编号" prop="moeMjbh">-->
          <!--                <el-input v-model="form.moeMjbh" placeholder="请输入模具编号" />-->
          <!--              </el-form-item>-->
        </el-col>
        <el-col :span="24">
          <el-form-item label="模具名称" prop="moeMjmc">
            <el-input v-model="form.moeMjmc" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="穴数" prop="moeXs">
            <el-input v-model="form.moeXs" placeholder="请输入穴数" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成型时间" prop="moeCxsj">
            <el-input v-model="form.moeCxsj" placeholder="请输入成型时间" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="生管备注" prop="moeDesc">
            <el-input v-model="form.moeDesc" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 移动工单对话框 -->
    <el-dialog
      :title="title"
      v-model="mobileOpen"
      :close-on-click-modal="false"
      draggable
      width="420px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-col :span="24">
          <el-form-item label="当前机台" prop="moeJtbh">
            <el-input v-model="form.moeJtbh" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="移动至机台" prop="mobileJtbh">
            <el-select v-model="mobileJtbh" filterable>
              <el-option
                v-for="dict in jtmList"
                :key="dict.jtmJtbh"
                :label="dict.jtmJtbh"
                :value="dict.jtmJtbh"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="mobileMoe">移 动</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMoeDet,
  getMoeDet,
  delMoeDet,
  stopMoeDet,
  updateMoeDet,
  mergeMoeDet,
  cMergeMoeDet,
  exportMoeDet,
  orderFinish,
  mobileMoeDet,
  listMoeDetJt,
} from "@/api/produce/moeDet";
import { listJtm } from "@/api/project/jtm";
import { getMofMjmByZzdh } from "@/api/produce/materialScheduling";
import debounce from "lodash/debounce";
import PopProductBom from "./PopProductBom.vue";
export default {
  name: "JtPlanMaintain",
  components: { PopProductBom },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      moeZzdhs: [],
      currDates: [],
      curZzdh: "",
      orderArr: [],
      // 非单个禁用
      single: true,
      // 非双个禁用
      doubles: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      openSearch: false,
      checked: false,
      checked2: false,
      // 总条数
      total: 0,
      // 工单表格数据
      moeDetList: [],
      tableH: document.body.clientHeight - 230,
      // 日期范围
      dateRange: [
        this.$moment().startOf("month").format(),
        this.$moment().add(1, "year").endOf("month").format(),
      ],
      //日期初始化
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //移动工单弹出层
      mobileOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 25,
        moeZzdh: null,
        moeSodh: null,
        moeJtbh: null,
        moeMjbh: null,
        itmPmgg: null,
        moeBbdm: null,
        flag: true,
        scflag: false,
      },
      // 表单参数
      form: {},
      mjmList: [],
      // 表单校验
      rules: {},
      //移动的机台
      mobileJtbh: null,
      countOrder: 0,
      //所有机台字典
      jtmList: [],
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      //工单状态字典
      moeZtbzOptions: [
        {
          label: "只显示未完成工单",
          value: 1,
        },
        {
          label: "只显示生产中工单",
          value: 2,
        },
      ],
    };
  },
  created() {
    //获取所有机台
    listJtm(null).then((res) => {
      this.jtmList = res.rows;
    });
    this.getList();
    this.getTreeselect();
    this.$store.dispatch("GetBomCgsx");
    this.$store.dispatch("GetCwOpt");
  },
  methods: {
    iCellStyle({ row, column, rowIndex, columnIndex }) {
      //启动
      if (row.moeZtbz == "1") {
        return "color:#09aa46";
      } else if (row.moeZtbz == "2") {
        return "color:#bb0331";
      } else if (row.moeZtbz == "3") {
        return "color:#4169E1";
      } else if (row.moeZtbz == "4 ") {
        return "color:#FAFFF0";
      }
    },
    getTreeselect() {
      this.deptOptions = [];
      listMoeDetJt(this.queryParams).then((response) => {
        this.deptOptions.push(response.data);
      });
    },
    //下拉
    changeSelect(el) {
      for (let i of this.mjmList) {
        if (el == i.mjm_mjbh) {
          this.form.moeMjmc = i.mjm_mjmc;
          this.form.moeXs = i.itd_xs;
          this.form.moeCxsj = i.mjm_cxsj;
        }
      }
    },
    handleOrder() {
      this.moeDetList.map((item) => {
        this.countOrder = 0;
        this.orderArr = [];
        item.moeScxh = null;
        item.moeScrq = null;
      });
    },
    handleOrderFinish() {
      if (this.orderArr.length > 0) {
        orderFinish(this.orderArr)
          .then((res) => {
            this.msgSuccess("排序成功");
          })
          .catch(() => {
            this.msgError("排序失败");
          });
      } else {
        alert("请先点击工单进行排序");
      }
    },
    clickRow(row) {
      if (row.moeScxh == null) {
        this.countOrder++;
        row.moeScxh = this.countOrder;
        row.moeScrq = this.rq();
      }
      const data = {
        moeId: row.moeId,
        moeScxh: row.moeScxh,
        moeScrq: row.moeScrq,
      };
      this.orderArr.push(data);

      // this.$refs.moeTable.toggleRowSelection(row)
    },
    rq() {
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      return yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
    },
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (this.dateRange !== null) {
        this.queryParams.params["beginDate"] = this.moment(
          this.dateRange[0]
        ).format("YYYY-MM-DD HH:mm:ss");
        this.queryParams.params["endDate"] = this.moment(
          this.dateRange[1]
        ).format("YYYY-MM-DD HH:mm:ss");
      }
      this.queryParams.pageNum = 1;
      listMoeDet(this.queryParams).then((response) => {
        this.moeDetList = [];
        this.moeDetList = this.moeDetList.concat(response.rows);
        this.total = response.total;
        this.loading = false;
      });
    },
    //load
    load: debounce(function () {
      if (
        this.queryParams.pageNum <
        Math.ceil(this.total / this.queryParams.pageSize)
      ) {
        this.queryParams.pageNum++;
        listMoeDet(this.queryParams).then((response) => {
          this.moeDetList = this.moeDetList.concat(response.rows);
          this.total = response.total;
          this.loading = false;
        });
      }
      return 0;
    }, 500),
    // 取消按钮
    cancel() {
      this.open = false;
      this.openSearch = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        moeId: null,
        moeZzdh: null,
        moeYwdh: null,
        moeSodh: null,
        moeWldm: null,
        itmPmgg: null,
        moeBbdm: null,
        moeJtbh: null,
        moeMjbh: null,
        moeMjmc: null,
        moeZtbz: null,
        moeScrq: null,
        moeScxh: null,
        moeScsl: null,
        moeCount: null,
        moeChsl: null,
        moeLpsl: null,
        moeBlsl: null,
        moeWxbl: null,
        moeTjbl: null,
        moeTzsl: null,
        moeKcsl: null,
        moeZcsxrq: null,
        moeSxrq: null,
        moeXxrq: null,
        moePredate: null,
        moeSjcxsj: null,
        moeTjsj: null,
        moeHmsj: null,
        moeSjsj: null,
        moeHssj: null,
        moeWgrq: null,
        moeKssj: null,
        moeJssj: null,
        moeXs: null,
        moeCxsj: null,
        moeGzzt: null,
        moeJzzl: null,
        moeSkzl: null,
        moeMzzl: null,
        moeZszl: null,
        moeGjzl: null,
        moeJlry: null,
        moeJlrq: null,
        moeGgry: null,
        moeGgrq: null,
        moeDesc: null,
        moeMofid: null,
        moeMolid: null,
        moeFhflag: null,
        moeSfdm: null,
        moeRkwl: null,
        moeCkdm: null,
        moeRksl: null,
        moeCzry: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.moeDetList = [];
      this.getList();
      this.getTreeselect();
      this.openSearch = false;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.currDates = selection;
      this.ids = selection.map((item) => item.moeId);
      this.moeZzdhs = selection.map((item) => item.moeZzdh);
      this.doubles = selection.length !== 2;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const moeId = row.moeId || this.ids;
      getMoeDet(moeId).then((response) => {
        this.form = response.data;
        getMofMjmByZzdh(response.data.moeZzdh).then((res) => {
          this.mjmList = res.data.mjmList;
          this.changeSelect(this.form.moeMjbh);
        });
        this.open = true;
        this.title = "修改工单";
      });
    },
    startJtEmpty(data) {
      for (let i of data) {
        if (i.moeZtbz == "1") return true;
      }
      return false;
    },
    /** 工单移动 */
    mobileMoe() {
      if (!this.mobileJtbh) {
        this.msgError("请选择机台");
        return;
      }
      if (this.startJtEmpty(this.currDates)) {
        alert("不能选择在生产的机台");
      } else {
        mobileMoeDet(this.ids, this.mobileJtbh).then((res) => {
          this.form = {};
          this.mobileJtbh = null;
          this.getList();
          this.mobileOpen = false;
          this.msgSuccess("移动成功");
        });
      }
    },
    /** 移动按钮操作 */
    handleMobile() {
      this.reset();
      let jtbh = "";
      for (let i of this.currDates) {
        if (jtbh.indexOf(i.moeJtbh) != 1) {
          jtbh += i.moeJtbh + ",";
        }
      }
      this.form.moeJtbh = jtbh.slice(0, jtbh.length - 1);
      this.mobileOpen = true;
      this.title = "工单机台移动";
    },
    /** 判断模具是否相同 */
    isMjbhSame(moeDets) {
      let mjbh = moeDets[0].moeMjbh;
      for (let i of moeDets) {
        if (i.moeMjbh != mjbh) return true;
      }
      return false;
    },
    isWldmSame(moeDets) {
      let moeWldm = moeDets[0].moeWldm;
      let i = 1;
      for (i; i < moeDets.length; i++) {
        if (moeWldm !== moeDets[i].moeWldm) {
          moeWldm = moeDets[i].moeWldm;
        } else {
          return true;
        }
      }
      return false;
    },
    /** 工单合并 */
    handleMerge() {
      let moeDets = this.currDates;
      if (moeDets.length < 2) {
        alert("请选取至少两张或以上工单进行组合");
      } else {
        if (this.isMjbhSame(moeDets)) {
          alert("所组合的工单模具编号不一致,无法进行组合");
        } else {
          if (this.isWldmSame(moeDets)) {
            alert("所组合得工单出现相同的物料,无法进行组合");
          } else {
            const moeIds = moeDets.map((item) => item.moeId);
            mergeMoeDet(moeIds).then((res) => {
              this.getList();
              this.msgSuccess("工单合并成功");
            });
          }
        }
      }
    },
    /** 取消合并 */
    handleCMerge() {
      const moeGlids = this.currDates.map((item) => item.moeGlid);
      if (moeGlids.length > 0) {
        cMergeMoeDet(moeGlids)
          .then((res) => {
            this.msgSuccess("工单取消合并成功~");
            this.getList();
          })
          .catch(() => {
            this.msgError("工单取消合并失败");
          });
      }
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.moeJtbh = null;
      this.queryParams.moeBbdm = null;
      if (data.label[data.label.length - 1] == "组") {
        this.queryParams.moeBbdm = data.id;
      } else {
        if (data.label !== "所有") this.queryParams.moeJtbh = data.label;
      }
      this.getList();
    },
    handleSearch() {
      this.reset();
      this.title = "查询工单";
      this.openSearch = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.moeId != null) {
            updateMoeDet(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete() {
      const moeIds = this.ids;
      this.$confirm(
        "确定将【制造单号：" +
          this.moeZzdhs +
          "】的工单删除吗?删除后将无法恢复，请谨慎操作",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delMoeDet(moeIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 暂停按钮操作 */
    handleStop() {
      const moeIds = this.ids;
      this.$confirm(
        "确定将【制造单号：" +
          this.moeZzdhs +
          "】的工单暂停吗?暂停后将无法生产，请谨慎操作",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return stopMoeDet(moeIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("暂停成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有工单数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportMoeDet(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计:";
          return;
        }
        if (
          !["moeLpsl", "moeSysl", "moeRksl", "moeDaycn", "moeScsl"].includes(
            column.property
          ) ||
          !column.property
        ) {
          sums[index] = " ";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = "N/A";
        }
      });

      return sums;
    },
  },
};
</script>

<style lang="scss" scoped></style>
